package com.soa.database.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.soa.database.entity.GatewayServiceTestGroup;
import com.soa.database.entity.GatewayServiceTestGroupLog;
import com.soa.database.entity.GatewayServiceTestLog;
import com.soa.database.service.GatewayTestService;
import com.soa.database.util.DyMethodUtil;


@Controller
@RequestMapping("apiTest")
public class GatewayTestController {
	
	@Autowired
	GatewayTestService gatewayTestService;
	
	/**
	 * 获得所有组的最新测试结果
	 * @param groupName
	 * @return
	 * @throws Exception
	 */
	@GetMapping("getGroupTestResult")
	@ResponseBody
	public Map<String,Object> getGroupTestResult(String groupName) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String sql="select a.* from gateway_service_test_group_log a,(select group_id,max(operate_time) operate_time from gateway_service_test_group_log group by group_id) b where a.operate_time = b.operate_time and a.group_id = b.group_id";
		if(!StringUtils.isEmpty(groupName)){
			sql+=" and a.group_name =:group_name";
		}
		Query query=gatewayTestService.getSession().createSQLQuery(sql).addEntity(GatewayServiceTestGroupLog.class);
		if(!StringUtils.isEmpty(groupName)){
			query.setString("group_name", groupName);
		}
		List<GatewayServiceTestGroupLog> result  = query.list();
		map.put("resultcode", 10000);
		map.put("resultmessage", "查询成功");
		map.put("response", result);
		return map;
	}
	
	/**
	 * 获得所有的组
	 * @return
	 * @throws Exception
	 */
	@GetMapping("getAllGroup")
	@ResponseBody
	public Map<String,Object> getAllGroup() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		Criteria criteria = gatewayTestService.getSession().createCriteria(GatewayServiceTestGroup.class);
		criteria.add(Restrictions.not(Restrictions.in("id", new Object[]{"root","index"})));
		List<GatewayServiceTestGroup> result  = criteria.list();
		map.put("resultcode", 10000);
		map.put("resultmessage", "查询成功");
		map.put("response", result);
		return map;
	}
	
	
	/**
	 * 获取的测试日志
	 * @param request
	 * @param response
	 * @param session
	 * @param groupName
	 * @throws Exception
	 */

	@GetMapping("getGroupTestLog")
	@ResponseBody
	public Map<String,Object>  getGroupTestLog(String groupName) throws Exception{
		SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String,Object> map = new HashMap<String,Object>();
		Criteria criteria = gatewayTestService.getSession().createCriteria(GatewayServiceTestGroupLog.class);
		criteria.addOrder(Order.desc("operateTime"));
		if(!StringUtils.isEmpty(groupName)){
			criteria.add(Restrictions.eq("groupName", groupName));
		}else{
			map.put("resultcode", 20011);
			map.put("resultmessage", "请输入指定的测试组");
			return map;
		}
		List<GatewayServiceTestLog> all =null;
		List<Map<String,Object>> result =new ArrayList<Map<String,Object>>();
		List<GatewayServiceTestGroupLog> listGrouplog = criteria.list();
		if(listGrouplog!=null && listGrouplog.size()>0){
			GatewayServiceTestGroupLog GatewayServiceTestGroupLog = listGrouplog.get(0);
			Criteria listSettingLog = gatewayTestService.getSession().createCriteria(GatewayServiceTestLog.class);
//			ListSetting listSettingLog = new ListSetting(GatewayServiceTestLog.class);
//			listSettingLog.where(Term.addEqual("gatewayServiceTestGroupLog.id", GatewayServiceTestGroupLog.getId()));
			listSettingLog.add(Restrictions.eq("gatewayServiceTestGroupLog.id", GatewayServiceTestGroupLog.getId()));
			all =  listSettingLog.list();
			for (GatewayServiceTestLog gatewayServiceTestLog : all) {
				Map<String,Object> gatewayServiceTestLogMap  = DyMethodUtil.convertToMap(gatewayServiceTestLog);
				if(gatewayServiceTestLog.getState()!=null && gatewayServiceTestLog.getState().contains("成功")){
					gatewayServiceTestLogMap.put("state", "1");
				}else{
					gatewayServiceTestLogMap.put("state", "0");
				}
				gatewayServiceTestLogMap.put("operateTime", sp.format(gatewayServiceTestLog.getOperateTime()));
				gatewayServiceTestLogMap.put("operateEndTime", sp.format(gatewayServiceTestLog.getOperateEndTime()));
				Iterator<String> iter = gatewayServiceTestLogMap.keySet().iterator();
				    while(iter.hasNext()){
				        String key = iter.next();
				        if("gatewayServiceTestGroupLog".equals(key) || "responseContent".equals(key) ){
				            iter.remove();
				        }
				}
				result.add(gatewayServiceTestLogMap);
			
			}
			
		}
		map.put("resultcode", 10000);
		map.put("resultmessage", "查询成功");
		map.put("response", result);
		return map;
	}
	
	
	@PostMapping("testGroup" )
	@ResponseBody
	public Map<String,Object> testGroup(String groupName) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		Criteria listSettingGroup = gatewayTestService.getSession().createCriteria(GatewayServiceTestGroup.class);
		listSettingGroup.add(Restrictions.eq("state", "1")).add(Restrictions.not(Restrictions.in("id", new Object[]{"root","index"})));
		if(!StringUtils.isEmpty(groupName)){
			listSettingGroup.add(Restrictions.eq("groupName", groupName));
		}else{
			map.put("resultcode", 20011);
			map.put("resultmessage", "请输入指定的测试组");
			return map;
		}
		List<GatewayServiceTestGroup> listGroup = listSettingGroup.list();
		if(listGroup.size()==0){
			map.put("resultcode", 20010);
			map.put("resultmessage", "未找到有效的测试组");
			return map;
		}
		try{
			gatewayTestService.checkService(groupName);
		}catch(Exception e){
			map.put("resultcode", 20012);
			map.put("resultmessage", "测试故障:"+e.getMessage());
			return map;
		}
		map.put("resultcode", 10000);
		map.put("resultmessage", "测试完成");
		return map;
	}
	
}
